<script src="../../main.js"></script>
<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-video-play"></i> 直播
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-lx-roundadd"
                        class="handle-del mr10"
                        @click="addItem"
                        v-if="globalPermission.live.add"
                >新增直播
                </el-button>
                <el-input v-model="query.title" placeholder="直播标题" class="handle-input mr10"></el-input>
                <el-select v-model="query.status" placeholder="状态" class="handle-input mr10">
                    <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-select v-model="query.playStatus" placeholder="类型" class="handle-input mr10">
                    <el-option
                            v-for="item in playStatusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <template>
                    <el-date-picker
                            v-model="timeValue"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="pickerOptions"
                            class="mr10">
                    </el-date-picker>
                </template>
                <el-button type="primary" icon="el-icon-search"  @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="title" label="直播标题"></el-table-column>
                <el-table-column label="封面图" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-lx-attention"
                                @click="handleImage(scope.row.id,scope.row.coverImg)"
                        >查看/上传</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template slot-scope="scope">
                        <el-tag
                                :type="scope.row.status==='1'?'success':(scope.row.status==='0'?'danger':'')"
                        >{{scope.row.status=='0'?"下架":"上架"}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="playStatus" label="类型">
                    <template slot-scope="scope">
                        <el-tag
                                :type="scope.row.playStatus==='0'?'success':(scope.row.playStatus==='1'?'danger':'')"
                        >{{scope.row.playStatus=='0'?"直播":"回放"}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="signCount" label="最大报名人数"></el-table-column>
                <el-table-column prop="signTime" label="报名开始时间"></el-table-column>
                <el-table-column prop="endTime" label="报名结束时间"></el-table-column>
                <el-table-column prop="createdTime" label="创建时间"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-thumb"
                                @click="handleLiveEdit(scope.row.id, scope.row)"
                                v-if="globalPermission.live.edit"
                        >直播流
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.row.id, scope.row)"
                                v-if="globalPermission.live.edit"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.row.id, scope.row)"
                                v-if="globalPermission.live.del"
                        >删除
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleStatus(scope.row.id,scope.row.status)"
                                v-if="globalPermission.news.one && scope.row.status==0"
                        >上架
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleStatus(scope.row.id,scope.row.status)"
                                v-if="globalPermission.news.two && scope.row.status==1"
                        >下架
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageNum"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <el-dialog title="封面图片" :visible.sync="imageVisible" width="40%">
            <el-table
                    :data="picData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="imageName" label="图片(点击预览大图)" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-thumb"
                                :src="picData[0]"
                                :preview-src-list="picData"
                        ></el-image>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
               <el-upload
                       ref="uploadPicture"
                       class="upload-demo"
                       action="/manager/tencent/uploadLiveImg"
                       :headers="getToken"
                       :before-upload="beforeUpload"
                       :data="uploadData"
                       :on-success="refreshPic"
                       multiple
               >
                    <el-button size="medium" type="primary" v-if="globalPermission.live.addpic">上传封面图</el-button>
                    <div slot="tip" class="el-upload__tip">友情提示：图片操作实时更新</div>
                </el-upload>
            </span>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="直播标题">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="可报人数">
                    <el-input v-model="form.signCount"></el-input>
                </el-form-item>
                <el-form-item label="推荐人">
                    <el-input v-model="form.recommend"></el-input>
                </el-form-item>
                <el-form-item label="直播人">
                    <el-input v-model="form.speaker"></el-input>
                </el-form-item>
                <el-form-item label="报名时间">
                    <template>
                        <el-date-picker
                                v-model="form.timeSelValue"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd"
                                :picker-options="pickerOptions"
                                class="mr10">
                        </el-date-picker>
                    </template>
                </el-form-item>
                <el-form-item label="直播时间">
                    <template>
                        <el-date-picker v-model="form.liveTime" type="datetime" placeholder="选择时间" @change="dataSearch" value-format="yyyy-MM-dd HH:mm:ss" ></el-date-picker>
                    </template>
                </el-form-item>
                <el-form-item label="摘要">
                    <el-input v-model="form.summary"></el-input>
                </el-form-item>
                <el-form-item label="直播介绍">
                    <quill-editor ref="myTextEditor" v-model="form.introduce" :options="editorOption3"></quill-editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="clean">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑直播流弹出框 -->
        <el-dialog title="编辑|查看" :visible.sync="editLiveVisible" width="60%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="流有效期">
                    <el-input v-model="form.validDay" placeholder="单位/小时；流地址的有效期，不填写则默认为12小时"></el-input>
                </el-form-item>
                <el-form-item label="推流地址">
                    <el-input v-model="form.pushFlow"></el-input>
                </el-form-item>
                <el-form-item label="推流秘钥">
                    <el-input v-model="form.secretKey" readOnly = "readOnly"></el-input>
                </el-form-item>
                <el-form-item label="观看地址">
                    <el-input v-model="form.pullFlow"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="clean">取 消</el-button>
                <el-button type="primary" @click="saveLiveEdit">生成直播流</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getAllLive, delLive, saveLive, editLive,createLiveFlow, getLiveDetail,updateStatus,getDetail} from '../../api/live';
    import {getAllTabs} from "../../api/tabs";
    import 'quill/dist/quill.snow.css' // 富文本编辑器外部引用样式  三种样式三选一引入即可
    import '@/utils/size-set.css';
    import {quillRedefine} from 'vue-quill-editor-upload'
    import { quillEditor,Quill } from 'vue-quill-editor';
    import {container, ImageExtend, QuillWatch} from 'quill-image-extend-module'
    Quill.register('modules/ImageExtend', ImageExtend);
    let fontSizeStyle = Quill.import('attributors/style/size');
    fontSizeStyle.whitelist = ['10px', '12px', '14px', '16px','18px','20px', '22px','24px', '26px', '28px','30px','32px', '36px','38px', '40px','45px', '50px', false];
    Quill.register(fontSizeStyle, true);
    //引入video样式
    import 'video.js/dist/video-js.css'
    import 'vue-video-player/src/custom-theme.css'

    var queryRequest = {url: "/manager/live/liveList"};
    var addRequest = {url: "/manager/live/addlive"};
    var updateRequest = {url: "/manager/live/updateLive"};
    var CreateFlowRequest = {url: "/manager/live/createLiveInfo"};
    var updateStatusRequest = {url: "/manager/live/updateStatus"};
    var delRequest = {url: "/manager/live/delLiveById"};
    var getLiveRequest ={url:"/manager/live/getLiveInfo"};
    export default {
        name: 'usertable',
        data() {
            return {
                query: {
                    title: '',
                    status: '',
                    playStatus: '',
                    startTime:'',
                    endTime:'',
                    pageNum: 1,
                    pageSize: 10
                },
                globalPermission: this.getPermission(),
                getToken:{'auth-token':localStorage.getItem('token')},
                uploadData:null,
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                editLiveVisible: false,
                editRolesVisible: false,
                formIdShow: false,
                isCurEdit: false,
                pageTotal: 0,
                form: {},
                picData:[],
                imageVisible:false,
                idx: -1,
                id: -1,
                statusOptions: [{
                    value: 0,
                    label: '下架'
                }, {
                    value: 1,
                    label: '上架'
                }],
                playStatusOptions:  [{
                   value: 0,
                   label: '直播'
               }, {
                   value: 1,
                   label: '回放'
               }],
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                statusQuery:{
                        id:'',
                        status
                },
                editorOption3: {
                    modules: {
                        toolbar: {
                            container: [
                                [{ indent: "-1" }, { indent: "+1" }], // 缩进
                                [{ size: fontSizeStyle.whitelist}], // 字体大小  ["small", false, "large", "huge"]
                                ["clean"] //上传图片、上传视频 //清除字体样式
                            ],
                            handlers: {
                                'image': function () {
                                    QuillWatch.emit(this.quill.id)
                                }
                            }
                        }
                    }
                },
                timeValue:'',
                timeSelValue:[],
            };
        },
        components:{
            quillEditor,quillRedefine
        },
        created() {
            queryRequest.data = this.query;
            this.getData();
            this.initData({});
        },
        methods: {
            // 获取数据
            getData() {
                //获取栏目列表
                getAllLive(queryRequest).then(res => {
                    this.tableData = res.data.list;
                    this.pageTotal = res.data.total;
                });
            },


            dataSearch() {
              this.getListByDataTime();
            },
            async initData(data) {
                  //获取当前时间
                  var now   = new Date();
                  var monthn = now.getMonth()+1;
                  var yearn  = now.getFullYear();
                  var dayn = now.getDate();
                  var h = now.getHours();
                  var m =now.getMinutes();
                  var s = now.getSeconds();
                  this.selectDatetime = yearn+"-"+monthn+"-"+dayn+" "+h+":"+m+":"+s;

                  this.selectUser = parseInt(sessionStorage.getItem("userid"));
                  this.getListByDataTime();
            },
             async getListByDataTime(data) {

            },
            clean(){
                this.editVisible=false;
                this.editLiveVisible = false;
                this.handleSearch();
            },
            // 打开图片窗口
            handleImage(id,url) {
                this.id=id;
                this.picData[0]=url;
                this.imageVisible = true;
            },
            refreshPic(){
                this.imageVisible = false;
                getLiveRequest.id =this.id;
                getLiveDetail(getLiveRequest).then(res=>{
                    this.picData[0] = res.data.coverImg;
                });
                this.handleSearch();
            },
            getPermission() {
                return JSON.parse(sessionStorage.getItem("permission"));
            },
            // 触发搜索按钮
            handleSearch() {
                this.query.startTime=this.timeValue[0];
                this.query.endTime=this.timeValue[1];
                this.$set(this.query, 'pageNum', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(id, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    delRequest.id = id;
                    delLive(delRequest).then(res => {
                        if (res.code == 0) {
                            this.$message.success(`删除成功`);
                            this.handleSearch();
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                    //this.tableData.splice(index, 1);
                }).catch(() => {
                });
            },

            //审核
            handleStatus(id,status){
                this.id= id;
                this.status=status;
                this.titleMsg = "确定要上架吗?";
                if(status == 1){
                    this.titleMsg = "确定要下架吗?";
                    this.status=0;
                }else{
                    this.status=1;
                }
                // 二次上下架
                this.$confirm(this.titleMsg, '提示', {
                    type: 'warning'
                }).then(() => {
                    this.statusQuery.id=this.id;
                    this.statusQuery.status=this.status;
                    updateStatusRequest.data = this.statusQuery;
                    updateStatus(updateStatusRequest).then(res => {
                        if (res.code == 0) {
                            this.$message.success(`成功`);
                            this.handleSearch();
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                }).catch(() => {
                });
            },

            // 新增
            addItem() {
                this.form={};
                this.editVisible = true;
                this.isCurEdit = false;
                this.editLiveVisible = false;
            },
            beforeUpload (file) {
                this.uploadData = {id:this.id};
                let promise = new Promise((resolve) => {
                    this.$nextTick(function () {
                        resolve(true);
                    });
                });
                return promise; //通过返回一个promis对象解决
            },
            // 编辑操作
            handleEdit(id, row) {
                this.id = id;
                getLiveRequest.id =this.id;
                getLiveDetail(getLiveRequest).then(res=>{
                   this.form = res.data;
                });
                this.editVisible = true;
                this.editLiveVisible = false;
                this.isCurEdit = true;
            },

            handleLiveEdit(id, row) {
              this.id = id;
              getLiveRequest.id =this.id;
              getLiveDetail(getLiveRequest).then(res=>{
                 this.form = res.data;
                 if(Object.keys(res.data.pushFlow).length!==0){
                    var secretKey = res.data.pushFlow.split('?');
                    this.form.secretKey = this.id+'?'+secretKey[1];
                 };
              });
              this.editVisible = false;
              this.editLiveVisible = true;
            },

            // 保存编辑
            saveEdit() {
                if (this.isCurEdit) {
                    updateRequest.data = this.form;
                    editLive(updateRequest).then(res => {
                        if (res.code == 0) {
                            this.$message.success(`修改成功`);
                            this.editVisible = false;
                            this.handleSearch();
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                } else {
                    addRequest.data = this.form;
                    saveLive(addRequest).then(res => {
                        if (res.code == 0) {
                            this.$message.success(`新增成功`);
                            this.editVisible = false;
                            this.handleSearch();
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                }
            },

            // 保存编辑
            saveLiveEdit() {
                // 二次确认重新生成
                this.$confirm('确定要生成或重新生成吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.form.id = this.id;
                    CreateFlowRequest.data = this.form;
                    createLiveFlow(CreateFlowRequest).then(res => {
                        if (res.code == 0) {
                            this.$message.success(`修改成功`);
                            getLiveRequest.id =this.id;
                            getLiveDetail(getLiveRequest).then(res=>{
                               this.form = res.data;
                               var secretKey = res.data.pushFlow.split('?');
                               this.form.secretKey = this.id+'?'+secretKey[1];
                            });
                        } else {
                            this.$message.error(res.message);
                        }
                    });
                }).catch(() => {
                });
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageNum', val);
                this.getData();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 130px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .show {
        display: block;
    }

    .hide {
        display: none;
    }

    .checkbox-rows {
        width: 130px;
        margin-top: 10px;
    }

    .el-checkbox.is-bordered + .el-checkbox.is-bordered {
        margin-left: 0px;
    }
</style>
